<?php

namespace IDock\Insurance\TAIC;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\TAIC\Request\AllTAICRequest;
use IDock\Insurance\TAIC\Request\PolicyPaymentRequest;
use IDock\Insurance\TAIC\Response\AllTAICResponse;
use IDock\Insurance\TAIC\Response\PolicyPaymentResponse;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return $this->config;
    }

    protected $config;

    protected $openId;

    protected $token;

    protected $sign;

    protected $pageUrl;

    public function execute(Request $request): Response
    {
        /*** @var AllTAICRequest $request */
        $request->loadConfig($this->config);

        $request->setRequestId(md5(uniqid()));

        $data = $this->generate($request);

        $header = [
            'openID' => $this->openId,
            'sign' => $this->sign,
            'token' => $this->token,
            'tradeType' => 'car',
            'tradeNo' => $request->getTradeNo(),
            'tradeDate' => date('Y-m-d H:i:s'),
        ];
        $data['requestHead'] = $header;
        $data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        $request->setPreParameter($data);
        $request->setBizParam($data);
        return $this->request($request);
    }

    /**
     * 获取支付链接
     * @param PolicyPaymentRequest $request
     * @return PolicyPaymentResponse
     */
    public function payment(PolicyPaymentRequest $request): PolicyPaymentResponse
    {
        $request->loadConfig($this->config);

        $requestId = sha1(uniqid('', true));

        $request->setRequestId($requestId);

        $param = $request->generate();

        $request->setBizParam($param);
        $payUrl = $request->getPayUrl();

        $response = new PolicyPaymentResponse(200);

        $response->setUrl($payUrl);
        return $response;
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        return $request;
    }

    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /*** @var AllTAICResponse $response */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        if ($response->isSuccess()) {
            $response->printerInit();
        }
        return $response;
    }

    public function encrypt(Request $request)
    {

    }
}


